﻿using System.Linq;
using housingsafety.server.Helpers;
using housingsafety.server.Svcs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace housingsafety.server.Filters
{
    public class DbAuthorizationFilter : IAuthorizationFilter
    {
        private readonly IUserTokenService _userTokenService;

        public DbAuthorizationFilter(IUserTokenService userTokenService)
        {
            _userTokenService = userTokenService;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.ActionDescriptor.EndpointMetadata
                .All(_ => _.GetType() != typeof(AllowAnonymousAttribute)))
            {
                var accessTokenSha256 = context.HttpContext.AccessToken()?.Sha256();
                if (!string.IsNullOrEmpty(accessTokenSha256))
                {
                    var currentUser = context.HttpContext.User.CurrentUser();
                    var tokens = _userTokenService.GetRefreshTokens(currentUser);
                    if (!tokens.Succ)
                    {
                        context.Result = new UnauthorizedObjectResult(new { msg = "user token revoked" }); // 返回未授权Result
                        return;
                    }

                    if (!tokens.Data.Tokens.ContainsKey(accessTokenSha256))
                    {
                        context.Result = new UnauthorizedObjectResult(new { msg = "user token revoked" }); // 返回未授权Result
                    }
                }
            }
        }
    }
}
